package com.sdx.console.meet.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CoreDictService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.meet.entity.MeetRecord;
import com.sdx.console.meet.entity.MeetServiceRecord;
import com.sdx.console.meet.service.MeetRecordService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * MeetRecord 接口
 */
@RequestMapping("/meet/meetRecord")
@Controller
public class MeetRecordController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(MeetRecordController.class);
    private static final String MODEL = "/meet/meetRecord";

    @Resource
	private MeetRecordService meetRecordService;

    @Resource
    private CustomerInfoService customerInfoService;

    @Resource
    private CoreDictService coreDictService;

    @Resource
    private CorePlatformService platformService;

    @Resource
    private CorePlatformService corePlatformService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private SQLManager sqlManager;


    /**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        //服务类型
        List serviceTypeList = coreDictService.findAllByType("SERVICE_TYPE");
        view.addObject("serviceTypeList",serviceTypeList);

        //服务老师
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setIsTeacher(1);
        List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
        view.addObject("customerInfoList",customerInfoList);
        Integer accessType = platformService.getAccessType(request);
        view.addObject("accessType",accessType);
        Integer provinceId =null;
        if (accessType.intValue()<6) {
            CoreOrg currentOrg = corePlatformService.getCurrentOrg();
            provinceId = currentOrg.getProvinceId();
        }
        view.addObject("provinceId",provinceId);
        view.addObject("provinceList",baseDataService.getAllProvince());
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("meet.meetRecord.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("meet.meetRecord.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Long meetId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        MeetRecord meetRecord = meetRecordService.queryById(meetId);
        view.addObject("meetRecord", meetRecord);
		setPageParam(view,request);
		try {
			view.addObject("meetRecordJson", JacksonUtils.toJsonString(meetRecord,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("meet.meetRecord.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("meet.meetRecord.query")
    @ResponseBody
    public JsonResult<PageQuery> list(MeetRecord condtion,HttpServletRequest request)
    {
        Integer accessType = platformService.getAccessType(request);
        if (accessType.intValue()==1) {
            CoreUser user = getLoginUser(request);
            String customerId = customerInfoService.getCustomerId(user.getId().intValue());
            if(StringUtils.isBlank(customerId)){
                customerId = "#";
            }
            condtion.setToCustomerid(customerInfoService.getCustomerId(user.getId().intValue()));
        }else if (accessType.intValue()==3) {
            CoreUser user = getLoginUser(request);
            condtion.setOrgId(user.getOrgId().intValue());
        }
        PageQuery page = condtion.getPageQuery();
        meetRecordService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,MeetRecord meetRecord,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			meetRecord.setCreatedTime(new Date());
			meetRecord.setUpdatedTime(new Date());
			meetRecordService.save(meetRecord);
		} else {
			meetRecord.setUpdatedTime(new Date());
			meetRecordService.updateTemplate(meetRecord);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("meet.meetRecord.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)MeetRecord meetRecord,HttpServletRequest request
		)
    {

        return save(true,meetRecord,request
		);
    }

    @PostMapping("/update.json")
    @Function("meet.meetRecord.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  MeetRecord meetRecord,HttpServletRequest request
		) {
		return save(false,meetRecord,request
		);
    }



    @GetMapping("/view.json")
    @Function("meet.meetRecord.query")
    @ResponseBody
    public JsonResult<MeetRecord>queryInfo(Long meetId) {
        MeetRecord meetRecord = meetRecordService.queryById( meetId);
        return  JsonResult.success(meetRecord);
    }

    @PostMapping("/delete.json")
    @Function("meet.meetRecord.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        meetRecordService.batchDelMeetRecord(idList);
        return JsonResult.success();
    }



    @GetMapping("/assign.do")
    @Function("meet.meetRecord.assign")
    @ResponseBody
    public ModelAndView assign(HttpServletRequest request,Integer meetId) {
        ModelAndView view = new ModelAndView(MODEL+"/assign.html") ;
        setPageParam(view,request);
        List<CustomerInfo> list = meetRecordService.queryMeetTeacher(meetId);
        view.addObject("teacherList",list);
        view.addObject("meetId",meetId);
        return view;
    }

    /**
     * 分配服务老师
     * @param meetRecord
     * @param request
     * @param record
     * @return
     */
    @PostMapping("/assign.json")
    @Function("meet.meetRecord.assign")
    @ResponseBody
    @Transactional
    public JsonResult<String> assignSave(MeetRecord meetRecord,HttpServletRequest request,
                                         MeetServiceRecord record ) {
        JsonResult result = JsonResult.success();

        CoreUser user = getLoginUser(request);
        String customerId = customerInfoService.getCustomerId(user.getId().intValue());
        if(StringUtils.isEmpty(customerId)){
            return JsonResult.failMessage("该账号没有关联会员");
        }

        meetRecord.setServiceStatus(1);
        meetRecord.setUpdatedTime(new Date());
        meetRecordService.updateTemplate(meetRecord);
        record.setCustomerId(customerId);
        record.setType(1);
        record.setCreatedTime(new Date());
        sqlManager.insertTemplate(record);

        return result;
    }


    @GetMapping("/service.do")
    @Function("meet.meetRecord.service")
    @ResponseBody
    public ModelAndView service(HttpServletRequest request,Integer meetId) {
        ModelAndView view = new ModelAndView(MODEL+"/service.html") ;
        setPageParam(view,request);
        List<CustomerInfo> list = meetRecordService.queryMeetTeacher(meetId);
        view.addObject("meetId",meetId);
        return view;
    }

    /**
     * 老师填写服务
     * @param record
     * @param request
     * @return
     */
    @PostMapping("/service.json")
    @Function("meet.meetRecord.service")
    @ResponseBody
    @Transactional
    public JsonResult<String> serviceSave(MeetServiceRecord record,HttpServletRequest request) {
        JsonResult result = JsonResult.success();
        CoreUser user = getLoginUser(request);
        String customerId = customerInfoService.getCustomerId(user.getId().intValue());
        if(StringUtils.isEmpty(customerId)){
            return JsonResult.failMessage("该账号没有关联会员");
        }
        record.setType(2);
        record.setCustomerId(customerId);
        record.setCreatedTime(new Date());
        sqlManager.insertTemplate(record);

        MeetRecord meetRecord = new MeetRecord();
        meetRecord.setMeetId(record.getMeetId().longValue());
        meetRecord.setUpdatedTime(new Date());
        meetRecordService.updateTemplate(meetRecord);
        return result;
    }

}
